package logic

import (
	"context"
	"encoding/json"
	"fmt"

	"dfx_cmdb/cmdb-account-management-rpc/internal/svc"
	cmdb_account_management_rpc "dfx_cmdb/cmdb-account-management-rpc/types/cmdb-account-management-rpc"
	cmdbaccountmanagement "dfx_cmdb/models/cmdb-account-management"

	"github.com/zeromicro/go-zero/core/logx"
	"gorm.io/datatypes"
	"gorm.io/gorm"
)

type UpdateAccessInfoLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUpdateAccessInfoLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdateAccessInfoLogic {
	return &UpdateAccessInfoLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}


func (l *UpdateAccessInfoLogic) UpdateAccessInfo(in *cmdb_account_management_rpc.UpdateAccessInfoRequest) (*cmdb_account_management_rpc.PublicResponse, error) {
	if in.Id <= 0 {
		logx.Errorf("无效的账号ID: %d", in.Id)
		return &cmdb_account_management_rpc.PublicResponse{
			Message: "无效的账号ID",
		}, fmt.Errorf("无效的账号ID")
	}

	// 先查询记录是否存在
	var existingAccount cmdbaccountmanagement.AccountManagement
	if err := l.svcCtx.PDB.WithContext(l.ctx).First(&existingAccount, in.Id).Error; err != nil {
		if err == gorm.ErrRecordNotFound {
			logx.Errorf("账号信息不存在，ID: %d", in.Id)
			return &cmdb_account_management_rpc.PublicResponse{
				Message: "账号信息不存在",
			}, fmt.Errorf("账号信息不存在")
		}
		logx.Errorf("查询账号信息失败: %v", err)
		return &cmdb_account_management_rpc.PublicResponse{
			Message: fmt.Sprintf("查询账号信息失败: %v", err),
		}, err
	}

	// 构建更新数据（只更新非空字段）
	updates := map[string]interface{}{}
	if in.Type != "" {
		updates["type"] = in.Type
	}
	if in.Platform != "" {
		updates["platform"] = in.Platform
	}
	if in.PlatformName != "" {
		updates["platform_name"] = in.PlatformName
	}
	if in.Account != "" {
		updates["account"] = in.Account
	}
	if in.Password != "" {
		updates["password"] = in.Password
	}
	if in.Token != "" {
		updates["token"] = in.Token
	}
	if in.Accesskey != "" {
		updates["accesskey"] = in.Accesskey
	}
	if in.Accesssecret != "" {
		updates["accesssecret"] = in.Accesssecret
	}
	if in.Comment != "" {
		updates["comment"] = in.Comment
	}
	// 处理 OtherInfo
	if len(in.OtherInfo) > 0 {
		if jsonBytes, err := json.Marshal(in.OtherInfo); err == nil {
			updates["other_info"] = datatypes.JSON(jsonBytes)
		}
	}

	if len(updates) == 0 {
		logx.Info("没有需要更新的字段")
		return &cmdb_account_management_rpc.PublicResponse{
			Message: "没有需要更新的字段",
		}, nil
	}

	// 更新记录
	if err := l.svcCtx.PDB.WithContext(l.ctx).
		Model(&cmdbaccountmanagement.AccountManagement{}).
		Where("id = ?", in.Id).
		Updates(updates).Error; err != nil {
		logx.Errorf("更新账号信息失败: %v", err)
		return &cmdb_account_management_rpc.PublicResponse{
			Message: fmt.Sprintf("更新账号信息失败: %v", err),
		}, err
	}

	logx.Infof("成功更新账号信息，ID: %d, 更新字段数: %d", in.Id, len(updates))
	return &cmdb_account_management_rpc.PublicResponse{
		Message: "更新账号信息成功",
	}, nil
}
